<template>
  <!-- 头部信息 -->
  <HeaderView title="登录中心" :hasBack='false' path=""></HeaderView>

  <!-- 表单项 -->
  <van-form @submit="onSubmit">
    <van-field
        v-model="email"
        name="email"
        label="邮箱"
        placeholder="邮箱"
        autocomplete="true"
        :rules="[{ required: true, message: '邮箱格式不正确', pattern: /^([a-zA-Z0-9])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z]{2,4})+$/ }]"
    />

    <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        autocomplete="true"
        :rules="[{ required: true, message: '密码长度6-10位,由数字和字母组成', pattern: /^[a-zA-Z0-9]{3,6}$/ }]"
    />

    <router-link to="/register" class="loginRegister">注册账号</router-link>

    <div style="margin: 16px;">
        <van-button round block type="success" native-type="submit">登录</van-button>
    </div>
  </van-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { UserLogin } from '@/api/loginRegister'
import HeaderView from '@/components/Header/IndexView.vue'
import { LoginType } from '@/type/loginRegister'
import { showToast } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { UserToken, ShopcartNum } from '@/pinia'
import { GetList } from '@/api/shopcart'

const router = useRouter()
const route = useRoute()
const { saveToken } = UserToken()
const { saveNum } = ShopcartNum()
const email = ref('')
const password = ref('')

// 登录
const onSubmit = async (values: LoginType) => {
  const toast1 = showToast({ type: 'loading', message: '登录中...', forbidClick: true, duration: 0 })

  const res = await UserLogin({ email: values.email, password: values.password })
  const res2 = await GetList('include=goods')
  try {
    if (res.status === 200) {
      toast1.close()
      saveToken(res.data.access_token)
      saveNum(res2.data.data.length)
      showToast({
        type: 'success',
        message: '登录成功',
        duration: 1000,
        forbidClick: true,
        onClose: () => {
          if (route.query.backTo === undefined) {
            router.push('/home')
          } else {
            router.push(`${route.query.backTo}`)
          }
          email.value = ''
          password.value = ''
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss" scoped>
@import './common.scss'
</style>
